/**
 * Created by kenkozheng on 2015/7/16.
 * 利用backbone的路由语法，建立极简，适用于手机浏览器的路由
 * 增加了*号路由，等于backbone的defaultAction
 */
(function (root) {
    var Route = root.Route = { init: function (map) { var defaultAction = map["*"]; if (defaultAction) { Route.defaultAction = defaultAction; delete map["*"]; } Route.routes = map; init(); onchange(); }, routes: {}, defaultAction: null };
    function onchange(onChangeEvent) { var newURL = onChangeEvent && onChangeEvent.newURL || window.location.hash; var url = newURL.replace(/.*#/, ""); var found = false; for (var path in Route.routes) { var reg = getRegExp(path); var result = reg.exec(url); if (result && result[0] && result[0] != "") { var handler = Route.routes[path]; handler && handler.apply(null, result.slice(1)); found = true; } } if (!found && Route.defaultAction) { Route.defaultAction(); } };
    /**
     * 引自backbone，非常牛逼的正则
     * @param route
     * @returns {RegExp}
     */
    function getRegExp(route) { var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; route = route.replace(escapeRegExp, "\\$&").replace(optionalParam, "(?:$1)?").replace(namedParam, function (match, optional) { return optional ? match : "([^/?]+)"; }).replace(splatParam, "([^?]*?)"); return new RegExp("^" + route + "(?:\\?([\\s\\S]*))?$"); };
    /**
     * 这段判断，引用于director：https://github.com/flatiron/director
     */
    function init() { if ("onhashchange" in window && (document.documentMode === undefined || document.documentMode > 7)) { if (this.history === true) { setTimeout(function () { window.onpopstate = onchange; }, 500); } else { window.onhashchange = onchange; } this.mode = "modern"; } else { throw new Error("sorry, your browser doesn't support route"); } };
})(window);
/*=================================================================================================================================================================================================*/
/*
 公共方法
 */
//Date format
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
//2010/1/1 or 2010-1-1  to Date
String.prototype.toDate = function () {
    var value = this.toString();
    //标红的这段是关键代码，将那个长字符串的日期值转换成正常的JS日期格式
    value = value.replace(/\/Date\((-?\d+)\)\//, '$1');
    dt = new Date(value);
    return dt;
};
//2010/01/01 12:11:12 or 2010-01-01 12:11:12 to Date
String.prototype.StringToDate = function () {
    var value = this.toString();
    var d = new Date();
    d.setYear(parseInt(value.substring(0, 4), 10));
    d.setMonth(parseInt(value.substring(5, 7) - 1, 10));
    d.setDate(parseInt(value.substring(8, 10), 10));
    d.setHours(parseInt(value.substring(11, 13), 10));
    d.setMinutes(parseInt(value.substring(14, 16), 10));
    d.setSeconds(parseInt(value.substring(17, 19), 10));
    return d;
};
//String trim
String.prototype.trim = function () {
    var str = this,
  	str = str.replace(/^\s\s*/, ''),
  	ws = /\s/,
  	i = str.length;
    while (ws.test(str.charAt(--i)));
    return str.slice(0, i + 1);
};
//添加或修改url参数
function addUrlParam(url, name, value) {
    var newUrl = "";
    var reg = new RegExp("(^|)" + name + "=([^&]*)(|$)");
    var tmp = name + "=" + value;
    if (url.match(reg) != null) {
        newUrl = url.replace(eval(reg), tmp);
    }
    else {
        if (url.match("[\?]")) {
            newUrl = url + "&" + tmp;
        }
        else {
            newUrl = url + "?" + tmp;
        }
    }
    return newUrl;
}

var ajaxDebug = window.location.hostname.toLowerCase().indexOf("swe313.cn") >= 0 || window.location.hostname.toLowerCase().indexOf("localhost") >= 0;

//帮助方法
var mHelper = {
    //浏览器内核
    browserUA: function () {
        var u = navigator.userAgent;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
            alipay: u.indexOf('Alipay') > -1, //是否支付宝 
            weixin: u.indexOf('MicroMessenger') > -1, //是否微信 
            qq: u.match(/\sQQ/i) == " qq" //是否QQ
        };
    }(),
    //浏览器语言
    language: (navigator.browserLanguage || navigator.language).toLowerCase(),
    //页面进入加载效果
    pageLoading: function () {
        var _bg = "#ffffff";//背景
        var _color = "#7575ec";//加载动画颜色 原来#F9C300
        //加载样式
        var _style = "<style type=\"text/css\" id=\"pageLoadingStyle\">#pageLoading{position:fixed;top:0px;right:0px;bottom:0px;left:0px;z-index:99999;background:" + _bg + "}.loadingCenter{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-pack: center;-webkit-justify-content: center;-ms-flex-pack: center;justify-content: center;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;-webkit-box-sizing:border-box;box-sizing:border-box;height:100%;width:100%;text-align:center;}.spinner{margin:0px auto;width:35px;height:50px;text-align:center;font-size:10px}.spinner>div{background-color:" + _color + ";height:100%;width:4px;margin-right:3px;display:inline-block;float:left;-webkit-animation:stretchdelay 1.2s infinite ease-in-out;animation:stretchdelay 1.2s infinite ease-in-out}.spinner .rect2{-webkit-animation-delay:-1.1s;animation-delay:-1.1s}.spinner .rect3{-webkit-animation-delay:-1s;animation-delay:-1s}.spinner .rect4{-webkit-animation-delay:-.9s;animation-delay:-.9s}.spinner .rect5{-webkit-animation-delay:-.8s;animation-delay:-.8s}@-webkit-keyframes stretchdelay{0%,40%,to{-webkit-transform:scaleY(.4)}20%{-webkit-transform:scaleY(1)}}@keyframes stretchdelay{0%,40%,to{transform:scaleY(.4);-webkit-transform:scaleY(.4)}20%{transform:scaleY(1);-webkit-transform:scaleY(1)}}</style>";
        //页面加载html
        var _html = "<div id=\"pageLoading\"><div class=\"loadingCenter\"><div class=\"spinner\"><div class=\"rect1\"></div><div class=\"rect2\"></div><div class=\"rect3\"></div><div class=\"rect4\"></div><div class=\"rect5\"></div></div></div></div>";
        document.write(_style);
        document.write(_html);
    },
    //隐藏页面加载
    hidePageLoading: function () {
        document.getElementById("pageLoading").style.display = "none";
    },
    //设置分享图片
    setShareImg: function () {
        //var _img = "http://7tszt4.com2.z0.glb.qiniucdn.com/Images/Template/640.tips.png";
        var _img = "/Themes/Common/img/shareTips.png";
        var _html = "<div id='shareWrap' onclick='mHelper.hideShare()' style='position:fixed;width:100%;height:100%;top:0;right:0;bottom:0;left:0;background-color:rgba(0,0,0,.7);z-index:9001;display:none;'><div style='width:100%;height:100%;background-image:url(" + _img + ");background-repeat:no-repeat;-webkit-background-size:contain;background-size:contain;background-position:top center;'></div></div>";
        var _div = document.createElement("div");
        _div.id = "ShareWrapper";
        _div.innerHTML = _html;
        document.body.appendChild(_div);
    },
    //显示分享
    showShare: function () {
        document.getElementById("shareWrap").style.display = "block";
    },
    //隐藏分享
    hideShare: function () {
        document.getElementById("shareWrap").style.display = "none";
    },
    //回到头部
    gotoTop: function () {
        document.documentElement.scrollTop = document.body.scrollTop = 0;
        //$("html,body").animate({scrollTop:0},700);
    },
    //验证  是否为空
    isNull: function (value) {
        //为空验证
        if (value == null || value == undefined || value == "") return true;
        return false;
    },
    //验证 是否是手机号
    isTel: function (value) {
        var phone = /^1[0-9][0-9]\d{8}$/;
        if (!phone.test(value)) return false;
        return true;
    },
    //验证 是否是身份证
    isCardNo: function (value) {
        // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
        var reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X|x)$/;
        if (!reg.test(value)) return false;
        return true;
    },
    //验证 是否是中文
    isChineseChar: function (value) {
        //只能输入中文
        var regChineseChar = /^[\u4e00-\u9fa5]+$/;
        if (!regChineseChar.test(value)) return false;
        return true;
    },
    //img error 图片错误设置默认图片
    nofind: function (value) {
        //图片错误
        var img = event.srcElement;
        img.src = value;
        img.onerror = null;
    },
    //url参数
    getQueryString: function (name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    },
    //js伪编码
    HTMLEncode: function (html) {
        var temp = document.createElement("div");
        (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
        var output = temp.innerHTML;
        temp = null;
        return output;
    },
    //js伪解码
    HTMLDecode: function (text) {
        var temp = document.createElement("div");
        temp.innerHTML = text;
        var output = temp.innerText || temp.textContent;
        temp = null;
        return output;
    },
};
mHelper.pageLoading();
//defaultHtmlWidth设置页面宽度缩放
//计算字体
(function (doc, win) {
    var minWidth = 320, designWidth = 750;
    if ("undefined" != typeof defaultHtmlWidth && !isNaN(defaultHtmlWidth)) {
        designWidth = defaultHtmlWidth;
    }
    var docEle = doc.documentElement,
        evt = "onorientationchange" in window ? "orientationchange" : "resize",
        fn = function () {
            var width = docEle.clientWidth;
            width = width < minWidth ? minWidth : width;
            width = width > designWidth ? designWidth : width;
            if (designWidth > 0)
                docEle.style.fontSize = 100 * (width / designWidth) + "px";
            setTimeout(function () {
                mHelper.hidePageLoading();
            }, 300);
        };
    win.addEventListener(evt, fn, false);
    win.addEventListener("resize", fn, false);
    doc.addEventListener("DOMContentLoaded", fn, false);
}(document, window));
//自定义jquery方法
(function ($) {
    var ajaxLoading = null;
    var _debug = ajaxDebug;
    //首先备份下jquery的ajax方法
    var _ajax = $.ajax;

    //重写jquery的ajax方法
    $.ajax = function (opt) {
        var IsErrpr;
        //备份opt中error和success方法
        var fn = {
            error: function (XMLHttpRequest, textStatus, errorThrown) { },
            success: function (data, textStatus) { }
        }
        if (opt.error) {
            IsErrpr = opt.error;
            fn.error = opt.error;
        }
        if (opt.success) {
            fn.success = opt.success;
        }
        //扩展增强处理
        var _opt = $.extend(opt, {
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //错误方法增强处理
                if (!IsErrpr) {
                    weui.alert("网络错误，请稍后重试！");
                }
                if (_debug) {
                    console.group(new Date().Format("yyyy/MM/dd hh:mm:ss S ") + (opt.url != undefined ? opt.url : "") + " ajax status:" + textStatus);
                    console.log(opt.data);
                    console.log(XMLHttpRequest);
                    console.groupEnd();
                }
                fn.error(XMLHttpRequest, textStatus, errorThrown);
            },
            success: function (data, textStatus) {
                //成功回调方法增强处理
                if (_debug) {
                    console.group(new Date().Format("yyyy/MM/dd hh:mm:ss S ") + (opt.url != undefined ? opt.url : "") + " ajax status:" + textStatus);
                    console.log(opt.data);
                    console.log(data);
                    console.groupEnd();
                }
                fn.success(data, textStatus);
            },
            beforeSend: function (XHR) {
                var IsAjaxLoading = 1;
                if ("undefined" != typeof defaultAjaxLoading && !isNaN(defaultAjaxLoading)) {
                    IsAjaxLoading = defaultAjaxLoading;
                }
                //提交前回调方法
                if (IsAjaxLoading == 1)
                    ajaxLoading = weui.loading("处理中...", {});
            },
            complete: function (XHR, TS) {
                //请求完成后回调函数 (请求成功或失败之后均调用)。
                if (ajaxLoading != null)
                    ajaxLoading.hide();
            }
        });
        return _ajax(_opt);
    };

    $.fn.mobileUpload = function (options) {
        var opts = $.extend($.fn.mobileUpload.defaults, options);
        $.fn.mobileUpload.Init($(this), opts);
    }
    $.fn.mobileUpload.Init = function (obj, opts) {
        //追加添加代码 //accept=\"image/gif,image/jpeg,image/jpg,image/png,image/svg\"  capture=\"camera\" 
        var addImghtml = $("<dl class=\"localResizeIMG3\"><dd class=\"addImg\"><input type=\"file\" accept=\"image/gif,image/jpeg,image/jpg,image/png,image/svg\" /><label></label></dd></dl>");
        obj.append(addImghtml);
        //删除
        obj.on("click", "dd span", function () {
            $(this).closest("dd").remove();
        });
        //上传图片
        obj.on("change", "input[type=\"file\"]", function () {
            var _file = this.files[0];
            lrz(this.files[0], { width: opts.width }).then(function (results) {
                // 处理成功会执行
                console.log(results);
                console.log(_file);
                var type = _file.type;
                var fileName = _file.name;
                var img = new Image();
                img.className = "itemImg";
                var dd = document.createElement('dd');
                $(dd).append($("<span>&nbsp;</span>"))
                dd.appendChild(img);
                //img.src = typeof src === 'string' ? src : results.base64;
                //obj.find(".addImg").before(dd);

                $.ajax({
                    type: 'Post',
                    url: '/MktApi/UploadFromBase64',
                    dataType: 'json',
                    data: { base64: results.base64, name: fileName, type: type },
                    success: function (data) {
                        if (data.Status == 1) {
                            var url = data.Data.HostUrl + data.Data.FileUrl;
                            img.src = url;
                            obj.find(".addImg").before(dd);
                        }
                    },
                    error: function (data) { }
                });
            });
            //老版本lrz用这个 新版用上面那个
            //lrz(_file, { width: opts.width }, function (results) {
            //     你需要的数据都在这里，可以以字符串的形式传送base64给服务端转存为图片。
            //    console.log(results);
            //    console.log(_file);
            //    var type = _file.type;
            //    var fileName = _file.name;
            //    var img = new Image();
            //    img.className = "itemImg";
            //    var dd = document.createElement('dd');
            //    $(dd).append($("<span>&nbsp;</span>"))
            //    dd.appendChild(img);
            //    img.src = typeof src === 'string' ? src : results.base64;
            //    obj.find(".addImg").before(dd);

            //    $.ajax({
            //        type: 'Post',
            //        url: '/MktApi/UploadFromBase64',
            //        dataType: 'json',
            //        data: { base64: results.base64, name: fileName, type: type },
            //        success: function (data) {
            //            if (data.Status == 1) {
            //                var url = data.Data.HostUrl + data.Data.FileUrl;
            //                img.src = url;
            //                obj.find(".addImg").before(dd);
            //            }
            //        },
            //        error: function (data) { }
            //    });

            //});
            this.value = null;
        });
        var Style = "<style type=\"text/css\" id=\"localResizeIMG3Style\">.localResizeIMG3{*zoom:1;width:100%;max-width:320px;margin:0 auto}.localResizeIMG3:after{content:\".\";display:block;height:0;visibility:hidden;clear:both}.localResizeIMG3 dd,.localResizeIMG3 dt{width:60px;height:60px;display:inline-block;position:relative;margin:15px 10px;float:left;-webkit-box-sizing:border-box;box-sizing:border-box}.localResizeIMG3 dd span{position:absolute;right:0;display:block;width:20px;height:20px;position:absolute;z-index:110;right:0;top:-10px;border-radius:30px;background-image:url();-weblkit-background-size:20px 20px;background-size:20px 20px;background-position:center center}.localResizeIMG3 dd img{width:60px;height:60px;display:inline-block;background-color:#cfcfcf}.localResizeIMG3 dd input[type=\"file\"]{display:block;position:absolute;z-index:100;left:0;top:0;width:100%;height:100%;opacity:0}.localResizeIMG3 dd label{width:60px;height:60px;line-height:60px;text-align:center;display:inline-block;background-color:#fff;border:1px solid #dddddd;color:#dddddd;font-size:26px;cursor:pointer;-webkit-box-sizing:border-box;box-sizing:border-box;background-image:url();background-position:center center;background-repeat:no-repeat}" +
            obj.selector + " .localResizeIMG3 dd:nth-child(" + (opts.count + 1) + ") {display:none;}" + "</style>";
        $("head").append(Style);
    };
    $.fn.mobileUpload.defaults = { width: 400, count: 8 };
})(jQuery);